package com.book.interceptor;

import com.book.exception.NoLoginException;
import com.book.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;


/**
 * @author SuperYu  2024/8/8
 */

public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    JwtUtil jwtUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        System.out.println("当前的请求路径是：" + uri);

        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        // 这句话，一定不能少，否则会有跨域问题
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        // 得到请求头中的token
        String token = request.getHeader("authentication");
        System.out.println("拦截器中-前端带过来的token:" + token);

        if (token == null) {
            response.getWriter().print("login first");
        } else {
            try {
                String userName = jwtUtil.parseToken(token);

                // 得到redis里面的token去比较
                String redisToken = stringRedisTemplate.opsForValue().get(userName);

                if (token.equals(redisToken)) {
                    // 秒为单位
                    Long expire = stringRedisTemplate.getExpire(userName);

                    System.out.println("当前token的过期时间：" + expire);

                    if (expire < 120) {
                        // 生成新的token
                        String newToken = jwtUtil.createToken(userName);
                        // 写回到客户端：
                        response.setHeader("authentication", newToken);
                        // 写到redis里面
                        stringRedisTemplate.opsForValue().set(userName, newToken, 1, TimeUnit.MINUTES);
                    }

                    return true;
                }
                throw new NoLoginException("登录异常!");
            } catch (ExpiredJwtException e) {
                throw new NoLoginException("对不起token已经过期！");
            } catch (SignatureException e) {
                throw new NoLoginException("token(密钥)不正确！");
            } catch (RuntimeException e) {
                throw new NoLoginException("token解析异常！！");
            }
        }
        return false;
    }
}
